package com.github.dongliusuo.sshtunneldemo;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.Random;

public class PortUtils {

    private static final int DEFAULT_MIN_PORT = 40000;

    private static final int DEFAULT_MAX_PORT = 60000;

    private static final int MAX_ATTEMPTS = 100;

    private PortUtils() {
        throw new UnsupportedOperationException("工具类不能被实例化！");
    }

    /**
     * 获取一个40000到60000之间的随机可用端口号
     *
     * @return 可用的端口号
     * @throws IOException 如果未能找到可用端口
     */
    public static int getRandomAvailablePort() {
        return getRandomAvailablePort(DEFAULT_MIN_PORT, DEFAULT_MAX_PORT);
    }

    public static int getRandomAvailablePort(int min, int max) {
        Random random = new Random();
        for (int i = 0; i < MAX_ATTEMPTS; i++) {
            int port = random.nextInt((DEFAULT_MAX_PORT - DEFAULT_MIN_PORT) + 1) + DEFAULT_MIN_PORT;
            if (isPortAvailable(port)) {
                return port;
            }
        }
        throw new RuntimeException("无法在 " + DEFAULT_MIN_PORT + " 到 " + DEFAULT_MAX_PORT + " 之间找到可用的端口。");
    }

    /**
     * 检查指定端口号是否可用
     *
     * @param port 要检查的端口号
     * @return 如果端口可用，返回 true；否则，返回 false
     */
    private static boolean isPortAvailable(int port) {
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            // 如果成功绑定，表示端口可用
            return true;
        } catch (IOException e) {
            // 端口被占用或无法访问
            return false;
        }
    }
}
